package com.xd.clap.utils;


import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {

    private static final String jwtToken = "123456Bmsbe!@#$$";

    // 根据用户ID生成
    public static String createToken(Integer userId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userID", userId);
        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, jwtToken)
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 6 * 60 * 60 * 1000));
        return jwtBuilder.compact();
    }
    // 根据手机号生成（无过期时间）
    public static String createToken(String phone) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("phone", phone);
        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, jwtToken)
                .setClaims(claims)
                .setIssuedAt(new Date());
        return jwtBuilder.compact();
    }
    public static Map<String, Object> checkToken(String token) {
        try {
            Jwt parse = Jwts.parser().setSigningKey(jwtToken).parse(token);
            return (Map<String, Object>) parse.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String token = JWTUtil.createToken(100);
        System.out.println(token);
        Map<String, Object> map = JWTUtil.checkToken(token);
        System.out.println(map);
    }
}
